//
// Created by Tony on 2024/1/27.
//

#include "BinaryFile.h"
#include <cstdint>
#include <vector>

using std::string;
using std::vector;

BinaryFile::BinaryFile(string absPath) : absPath(std::move(absPath)), cursor(0) {}

void BinaryFile::append(const char* buf, size_t len) {
    auto oldSize = content.size();
    auto newSize = content.size() + len;
    content.resize(newSize);
    for (auto i = 0; i < len; i++) {
        content[oldSize + i] = buf[i];
    }
}

uint8_t BinaryFile::readUint8() { return content[cursor++]; }

uint16_t BinaryFile::readUint16() {
    uint8_t h = content[cursor++];
    uint8_t l = content[cursor++];
    return (static_cast<uint16_t>(h) << INT8_BITS) | l;
}

uint32_t BinaryFile::readUint32() {
    uint32_t ret = 0;
    for (int i = 0; i < INT32_BITS / INT8_BITS; ++i) {
        ret <<= INT8_BITS;
        ret |= static_cast<uint8_t>(content[cursor++]);
    }
    return ret;
}

uint64_t BinaryFile::readUint64() {
    uint64_t ret = 0;
    for (int i = 0; i < INT64_BITS / INT8_BITS; ++i) {
        ret <<= INT8_BITS;
        ret += static_cast<uint8_t>(content[cursor++]);
    }
    return ret;
}

vector<uint16_t> BinaryFile::readUint16s() {
    uint16_t n = readUint16();
    vector<uint16_t> ret(n);
    for (int i = 0; i < n; ++i) {
        ret[i] = readUint16();
    }
    return ret;
}

vector<char> BinaryFile::readBytes(size_t n) {
    vector<char> bytes(n);
    for (int i = 0; i < n; ++i) {
        bytes[i] = content[cursor++];
    }
    return bytes;
}
